package com.swx.guard.scheduling;

import com.swx.guard.bean.Service;
import com.swx.guard.util.ServiceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * @author Ricky
 * @date 2020/12/4
 */
@Slf4j
public class UpdateServiceTask {

    public static Map<String, ScheduledFuture<?>> taskList = new HashMap<>();

    public static void addTask(Service service, String cron) {
        String name = service.getName();
        log.info("添加【{}】定时任务:{}", name, cron);
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.initialize();
        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(
                () -> {
                    log.info("开始更新【{}】", name);
                    ServiceUtil.updateService(service);
                    log.info("更新完成【{}】", name);
                    // 取消掉，只执行一次
                    ScheduledFuture<?> f = taskList.get(name);
                    if (f != null) {
                        f.cancel(true);
                        taskList.remove(name);
                        log.info("取消【{}】定时任务", name);
                    }
                }, triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext)
        );
        taskList.put(name, future);
        log.info("添加【{}】定时任务成功", name);
    }

    public static boolean hasTask(Service service) {
        ScheduledFuture<?> f = taskList.get(service.getName());
        return f != null && !f.isCancelled();
    }
}
